#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <openssl/rsa.h>
#include <openssl/pem.h>
#include <openssl/err.h>
#include <sys/stat.h>
#include <sys/types.h>
#include "pub_header.h"

static RSA * gpRsaPubKey;
static RSA * gpRsaPriKey;

static void ByteToHexStr(const unsigned char* source, unsigned char* dest, int sourceLen)
{
    short i;
    unsigned char highByte, lowByte;

    for (i = 0; i < sourceLen; i++)
    {
        highByte = source[i] >> 4;
        lowByte = source[i] & 0x0f ;


        highByte += 0x30;


        if (highByte > 0x39)
            dest[i * 2] = highByte + 0x07;
        else
            dest[i * 2] = highByte;


        lowByte += 0x30;
        if (lowByte > 0x39)
            dest[i * 2 + 1] = lowByte + 0x07;
        else
            dest[i * 2 + 1] = lowByte;
    }
}

int sxsb_get_rsakey(const char *OPENSSLKEY,const char *PUBLICKEY)
{
    FILE *fpRd = NULL;
    fpRd = fopen(PUBLICKEY, "rb");
    if(!fpRd)
    {   
        return -1;
    }
    
    if((PEM_read_RSA_PUBKEY(fpRd, &gpRsaPubKey,NULL,NULL )) == NULL)
    {   
        fclose(fpRd);
        return -1;
    }
    
    fclose(fpRd);
    
    fpRd = fopen(OPENSSLKEY, "rb");
    if(!fpRd)
    {   
        return -2;
    }
    
    if((PEM_read_RSAPrivateKey(fpRd, &gpRsaPriKey, NULL, NULL )) == NULL)
    {
        fclose(fpRd);
        return -2;
    }

    fclose(fpRd);
        return 0;
}

char * get_xml_data(const char * xmlFile)
{
	char * text;
	FILE * fp = fopen(xmlFile,"r");
	fseek(fp,0,SEEK_END);
	long int size = ftell(fp);
	text = (char *)malloc(size + 1);
	rewind(fp);
	fread(text,sizeof(char),size,fp);
	text[size] = '\0';
	fclose(fp);
	return text;
}

char * sxsb_rsa_get_sign_byprikey(const char * xmlFile)
{
	const char * source = get_xml_data(xmlFile);
	char aczSign[256+1];
	char * sign = (char *)malloc(256 + 1);
	int iSignLen = 0;
	unsigned char hash[SHA_DIGEST_LENGTH]="";
	SHA1((unsigned char *)source,strlen(source),hash);
	memset(aczSign, 0x00, sizeof(aczSign));
	memset(sign,0x00,(size_t)sizeof(sign));
	RSA_sign(NID_sha1,hash,SHA_DIGEST_LENGTH,(unsigned char *)aczSign,(unsigned int *)&iSignLen, gpRsaPriKey);
	ByteToHexStr((const unsigned char *)aczSign, (unsigned char *)sign, iSignLen);
	free((void *)source);
	return sign;
}

